﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Net;
using System.Collections.ObjectModel;
using Board1.Info;
using Board1.Unleashed;
using System.Threading;
using System.Windows;
using System.Windows.Input;
namespace Board1.GetData
{
    public class DataBoard200 : INotifyPropertyChanged
    {
        // link cac bang xep hang
        string[] link = { "http://www.billboard.com/charts/billboard-200",
                        "http://www.billboard.com/charts/billboard-200?page=1",
                        "http://www.billboard.com/charts/billboard-200?page=2",
                        "http://www.billboard.com/charts/billboard-200?page=3",
                        "http://www.billboard.com/charts/billboard-200?page=4",
                        "http://www.billboard.com/charts/billboard-200?page=5",
                        "http://www.billboard.com/charts/billboard-200?page=6",
                        "http://www.billboard.com/charts/billboard-200?page=7",
                        "http://www.billboard.com/charts/billboard-200?page=8",
                        "http://www.billboard.com/charts/billboard-200?page=9"};
        public DataBoard200()
        {
            getDataTop200(link[0]);

            //bat su kien khi keo xuong duoi man hinh
            fetchMoreDataCommand = new DelegateCommand(
                obj =>
                {
                    if (busy)
                    {
                        return;
                    }
                    Busy = true;
                    ThreadPool.QueueUserWorkItem(
                        delegate
                        {
                            Thread.Sleep(3000);
                            Deployment.Current.Dispatcher.BeginInvoke(
                                delegate
                                {
                                    if (_topHot200Albums.Count <= 200)
                                        AddMoreItems();
                                    Busy = false;
                                });
                        });

                });
        }

        private WebClient downloadURL = new WebClient();
        string webData = null;
        private int start = 0, des1 = 0, des2 = 0;

        private static ObservableCollection<HubTileItem> _hubList = new ObservableCollection<HubTileItem>();
        public static ObservableCollection<HubTileItem> HubList
        {
            get { return _hubList; }
        }

        private static ObservableCollection<AlbumData> _topHot200Albums= new ObservableCollection<AlbumData>();
        public static ObservableCollection<AlbumData> TopHot200Albums
        {
            get { return _topHot200Albums; }
        }

        // tai them du lieu cho toi khi day du noi dung
        private void AddMoreItems()
        {
            start = 0;
            int i = _topHot200Albums.Count / 20;
            getDataTop200(link[i]);
        }

        // download du lieu html
        public void getDataTop200(string link)
        {
            try
            {
                downloadURL.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
                downloadURL.DownloadStringAsync(new Uri(link));
            }
            catch (System.Exception)
            {

                MessageBox.Show("Internet Connection Error", "Error", MessageBoxButton.OK);
            }
        }

        private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                webData = (string)e.Result;
                htmlHandler(webData);
                setListHubTile();
                
            }
            else
            {
                MessageBox.Show("Error");
            }
        }

        // xu li noi dung html de thu thap noi dung
        private void htmlHandler(string webData)

        {
            while (start < webData.Length && des1 != -1)
                {
                    AlbumData newItem = new AlbumData();
                    des1 = webData.IndexOf("<article id", start);
                    if (des1 == -1) break;
                    des2 = webData.IndexOf("</header>", des1);
                    if (webData.Substring(des1, des2 - des1).Contains("song_review"))
                    {
                        //lay ten album
                        int albumStart = webData.IndexOf("<h1>", des1);
                        int albumEnd = webData.IndexOf("</h1>", albumStart);
                        newItem.albumName = webData.Substring(albumStart + 4, albumEnd - albumStart - 4);

                        //lay vi tri
                        newItem.albumPosstion = (_topHot200Albums.Count + 1).ToString();

                        //lay thong tin artist
                        int artistEnd;
                        des2 = webData.IndexOf("</p>", albumEnd);
                        if (webData.Substring(albumEnd, des2 - albumEnd).Contains("<a href"))
                        {
                            int artistStart = webData.IndexOf("<a href", albumEnd);
                            artistStart = webData.IndexOf(">", artistStart);
                            artistEnd = webData.IndexOf("</a>", artistStart);
                            newItem.albumArtist = webData.Substring(artistStart + 1, artistEnd - artistStart - 1);
                        }
                        else
                        {
                            int artistStart = webData.IndexOf(">", albumEnd + 5);
                            artistEnd = webData.IndexOf("</p>", artistStart);
                            newItem.albumArtist = webData.Substring(artistStart + 9, artistEnd - artistStart - 19);
                        }
                        //lay img Source
                        int imgStart = webData.IndexOf("<img ", artistEnd);
                        imgStart = webData.IndexOf("src=", imgStart);
                        int imgEnd = webData.IndexOf("alt", imgStart);
                        string img = webData.Substring(imgStart + 5, imgEnd - imgStart - 7);
                        if (img.Contains("no-album.png")) img = "http://www.billboard.com/sites/all/themes/bb/images/default/no-album.png";
                        newItem.albumCover = img;

                        _topHot200Albums.Add(newItem);
                        start = des2 + 1;
                    }
                    else
                    {
                        webData = null;
                        break;
                    }
                }
        }

        // tạo noi dung cho hubtile
        private void setListHubTile()
        {
            for (int i = _hubList.Count; i < _topHot200Albums.Count; i++)
            {
                HubTileItem newItem = new HubTileItem();
                AlbumData temp = _topHot200Albums[i];
                newItem.uriSource = temp.albumCover;
                newItem.title = "by \"" + temp.albumArtist + "\"";
                newItem.message = "NO " + temp.albumPosstion + " ." + "\"" + temp.albumName + "\"";
                newItem.notification = temp.albumPosstion + " . " + temp.albumName;
                _hubList.Add(newItem);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var tempEvent = PropertyChanged;
            if (tempEvent != null)
            {
                tempEvent(this, e);
            }
        }

        private bool busy;
        public bool Busy
        {
            get { return busy; }
            set
            {
                if (busy == value)
                {
                    return;
                }
                busy = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Busy"));
            }
        }
        readonly DelegateCommand fetchMoreDataCommand;

        public ICommand FetchMoreDataCommand
        {
            get { return fetchMoreDataCommand; }
        }
    }
}
